package com.zjw.touchscreen.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.zjw.touchscreen.R;
import com.zjw.touchscreen.bluetooth.BluetoothListItem;
import lombok.Getter;

import java.util.ArrayList;
import java.util.List;

@Getter
public class BluetoothSpinnerAdapter extends BaseAdapter {

    private List<BluetoothListItem> bluetoothListItems = new ArrayList<>();

    private Context context;

    public BluetoothSpinnerAdapter(Context context) {
        this.context = context;
    }

    public void refresh(BluetoothListItem bluetoothListItem) {
        for (BluetoothListItem listItem : bluetoothListItems) {
            if(listItem.getAddr().equals(bluetoothListItem.getAddr())){
                return;
            }
        }
        bluetoothListItems.add(bluetoothListItem);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return bluetoothListItems.size();
    }

    @Override
    public BluetoothListItem getItem(int position) {
        return bluetoothListItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.bluetooth_item, null);
        BluetoothListItem bluetoothListItem = getItem(position);
        ImageView bluetoothIcon = view.findViewById(R.id.bluetooth_icon);
        TextView bluetoothName = view.findViewById(R.id.bluetooth_name);
        TextView bluetoothAddr = view.findViewById(R.id.bluetooth_addr);
        TextView bluetoothStatus = view.findViewById(R.id.bluetooth_status);
        bluetoothIcon.setBackground(bluetoothListItem.getIcon());
        bluetoothName.setText(bluetoothListItem.getName());
        bluetoothAddr.setText(bluetoothListItem.getAddr());
        bluetoothStatus.setText(bluetoothListItem.getStatus());
        return view;
    }
}
